package com.sky.service.impl;

import com.sky.annotation.AutoFile;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.enumeration.OperationType;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetMealDishMapper setmealDishMapper;

    /**
    *  新增菜品 & 口味
    * */
    @Transactional
    @Override
    public void saveDishAndFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        // 将DTO用方法快速拷贝到实体类中，不用再getter和setter
        BeanUtils.copyProperties(dishDTO, dish);
        log.info("新增菜品，数据：{}", dish);
        // 插入菜品数据
        dishMapper.insertDish(dish);

        // useGeneratedKeys="true" keyProperty="id"给id赋值后
        long id = dish.getId();
        //插入 口味爱好数据,先获取集合
        // 前端输入数据，后端处理数据，后端处理数据，前端展示数据，List集合只接受口味
        List<DishFlavor> dishFlavorsList = dishDTO.getFlavors();

        // 判断前端是否传回口味数据
        if (dishFlavorsList != null && dishFlavorsList.size() > 0){
            /// 遍历集合，给每个口味对象设置相同id，因为口味有多个
//            for(DishFlavor df : dishFlavorsList){
//                df.setDishId(id);
//            }
            dishFlavorsList.forEach(dishFlavor -> dishFlavor.setDishId(id));
            dishMapper.insertDishFlavor(dishFlavorsList);
        }
    }

    /**
    *  分页查询
    * */

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        Dish dish = new Dish();
        long total = dishMapper.count();

        BeanUtils.copyProperties(dishPageQueryDTO,dish);
        int start = (dishPageQueryDTO.getPage() - 1) * dishPageQueryDTO.getPageSize();

        List<DishVO> dishList = dishMapper.pageShow(dish.getCategoryId(),dish.getName(),
               dish.getStatus(),start,dishPageQueryDTO.getPageSize());
        return new PageResult(total,dishList);
    }

    /**
     *  根据id查询
     * */

    @Transactional
    @Override
    public DishVO getById(Long id) {
       /// category与dish联合查询
       DishVO dishVOAll = dishMapper.getByPathId(id);
       /// 菜品口味查询返回
       List<DishFlavor> dishFlavorList = dishMapper.selectDishFlavor(id);
       /// 将获得的dishFlavorList赋给dishVOAll中 List<DishFlavor>flavors集合中，最后一起返回给前端
       dishVOAll.setFlavors(dishFlavorList);
       return dishVOAll;
    }

    /**
     *  删除和批量删除
     * */
    @Transactional
    @Override
    public void deleteById(List<Long> ids) {
        /// 判断菜品是否起售
        for (Long id : ids) {
            ///  遍历查询获取状态
            Dish dish = dishMapper.getById(id);
            /// 判断是否在起售StatusConstant.ENABLE == 1
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        /// 判断是否菜品有关联
        List<Long> setmealIds = setmealDishMapper.getSetmealIdByDishId(ids);
        if (setmealIds != null && setmealIds.size() > 0){
            /// 抛出异常，菜品有关联
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        /// 删除菜品

            dishMapper.deleteById(ids);

        /// 删除菜品口味,可以用mybatis的foreach
            dishMapper.deleteDishFlavor(ids);

    }

    /**
     *  起售与停售
     * */
    @Override
    @AutoFile(value = OperationType.UPDATE)
    public void setStatus(Integer status, Long id) {
        dishMapper.setStatus(status,id);
    }

    /**
     *  修改菜品,有集合
     * */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        /// 前端会传回dish的id，因为id路径查询返回所有数据
        /// 1、修改菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateDish(dish);

        /// 2、将菜品中的口味集合取出并保存修改
        List<DishFlavor> dishFlavorsList = dishDTO.getFlavors();
        List<Long> FlavorDishIdList = new ArrayList<>();
        // 将菜品id获取并传入进集合中，因为mapper中接收的是集合
        FlavorDishIdList.add(dishDTO.getId());
        /// 3、删除菜品口味
        dishMapper.deleteDishFlavor(FlavorDishIdList);
        /// 4、判断修改的数据是否为空，不为空就执行
        if(dishFlavorsList != null && dishFlavorsList.size()>0 ){

            for (DishFlavor df : dishFlavorsList) {
                // 因为前面删除行会丢失Id消息
                df.setDishId(dishDTO.getId());
                dishMapper.updateDishFlavor(df);
            }
        }
    }

    /**
     *  根据categoryId查询信息
     * @return List<Dish>
     * */
    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();

        List<Dish> categoryIdList = dishMapper.getByCategoryId(dish);
        return categoryIdList;
    }
                                        /*User*/
    /*-----------------------------------------------------------------------------*/
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {

            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishMapper.selectDishFlavor(d.getId());

            dishVO.setFlavors(flavors);
            /// 将dishList中的数据复制到dishVOList中
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
